<template>
	<div>
		<el-card style="margin-bottom: 10px">
			<template #header>
				<span>查询条件</span>
			</template>
			<el-form label-width="auto">
				<el-row justify="space-between">
					<el-col :span="8">
						<el-form-item label="帖子类型">
							<el-select v-model="searchForm.category" placeholder="请选择类型" clearable>
								<el-option label="党建动态" value="党建动态"></el-option>
								<el-option label="学习心得" value="学习心得"></el-option>
								<el-option label="经验交流" value="经验交流"></el-option>
								<el-option label="其他" value="其他"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="帖子标题">
							<el-input v-model="searchForm.title" placeholder="请输入帖子标题" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8" style="display: flex;justify-content: right">
						<el-form-item label="发布人">
							<el-input v-model="searchForm.author" placeholder="请输入发布人" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row justify="space-between">
					<el-col :span="8">
						<el-form-item label="审核状态">
							<el-select v-model="searchForm.status" placeholder="请选择审核状态" clearable>
								<el-option label="待审核" value="0"></el-option>
								<el-option label="已通过" value="1"></el-option>
								<el-option label="已拒绝" value="2"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="发布时间">
							<el-date-picker v-model="searchForm.postDate" style="width: 400px;" format="yyyy-MM-dd"
								value-format="yyyy-MM-dd" />
						</el-form-item>
					</el-col>
					<el-col :span="8" style="display: flex;justify-content: right">
						<el-form-item>
							<el-button size="small" type="primary" icon="el-icon-search"
								@click="fetchData(1)">搜索</el-button>
							<el-button size="small" type="primary" icon="el-icon-refresh"
								@click="resetSearch">重置</el-button>
							<!-- <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd">发布新帖</el-button> -->
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-card>
		<!-- 查询结果 -->
		<el-card>
			<template #header>
				<div style="display: flex; justify-content: space-between; align-items: center">
					<span>查询结果</span>
					<div>
						<el-button type="primary" size="small" icon="el-icon-plus" @click="handleAdd">发布新帖</el-button>
					</div>
				</div>
			</template>

			<el-table :data="tableData" border style="width: 100%">
				<el-table-column prop="title" label="帖子标题" show-overflow-tooltip></el-table-column>
				<el-table-column label="封面图" width="100" align="center">
					<template slot-scope="scope">
						<el-image v-if="scope.row.pic" style="width: 60px; height: 60px" :src="scope.row.picUrl">
						</el-image>
						<span v-else>无封面</span>
					</template>
				</el-table-column>
				<el-table-column prop="category" label="帖子类型" width="120" align="center"></el-table-column>
				<el-table-column prop="author" label="发布人" width="120" align="center"></el-table-column>
				<el-table-column prop="postDate" label="发布时间" width="180" align="center" sortable></el-table-column>
				<el-table-column prop="status" label="审核状态" width="100" align="center">
					<template slot-scope="scope">
						<span v-if="scope.row.status == 0">待审核</span>
						<span v-if="scope.row.status == 1">审核通过</span>
						<span v-if="scope.row.status == 2">审核不通过</span>
					</template>
				</el-table-column>
        <el-table-column prop="remark" label="备注" width="150" align="center"></el-table-column>
				<el-table-column label="操作" width="280" align="center" fixed="right">
					<template slot-scope="scope">
						<el-button size="mini" type="primary" @click="handleView(scope.row)">查看</el-button>
						<el-button size="mini" type="warning" @click="handleEdit(scope.row)">编辑</el-button>
						<!-- <el-button size="mini" type="success" @click="handleAudit(scope.row)">审核</el-button> -->
						<el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<div class="pagination-container">
				<el-pagination background @current-change="handleCurrentChange"
					layout="total, prev, pager, next, jumper" :total="total">
				</el-pagination>
			</div>
		</el-card>

		<!-- 新增/编辑帖子对话框 -->
		<el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="70%" :close-on-click-modal="false">
			<el-form :model="postForm" :rules="rules" ref="postForm" label-width="100px">
				<el-form-item label="帖子类型" prop="topicType">
					<el-select v-model="postForm.category" placeholder="请选择类型">
						<el-option label="党建动态" value="党建动态"></el-option>
						<el-option label="学习心得" value="学习心得"></el-option>
						<el-option label="经验交流" value="经验交流"></el-option>
						<el-option label="其他" value="其他"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="帖子标题" prop="title">
					<el-input v-model="postForm.title" placeholder="请输入帖子标题"></el-input>
				</el-form-item>
				<el-form-item label="封面图片">
					<el-upload class="avatar-uploader" action="http://localhost:3000/api/uploadpic"
						:show-file-list="false" :on-success="handleCoverSuccess" :before-upload="beforeCoverUpload">
						<img v-if="postForm.pic" :src="postForm.picUrl" class="avatar">
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
					<div class="upload-tip">建议尺寸：800x400px，支持jpg、png格式</div>
				</el-form-item>
				<el-form-item label="帖子内容" prop="content">
					<el-input type="textarea" v-model="postForm.content" :rows="6" placeholder="请输入帖子内容"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="submitForm">确 定</el-button>
			</div>
		</el-dialog>

		<!-- 查看帖子对话框 -->
		<el-dialog title="帖子详情" :visible.sync="viewDialogVisible" width="80%">
			<div class="post-detail">
				<div class="post-header">
					<h2 class="post-title">
						{{ currentPost.title }}
					</h2>
					<div class="post-meta">
						<span>类型：{{ currentPost.category }}</span>
						<span>作者：{{ currentPost.author }}</span>
						<span>发布时间：{{ currentPost.postDate }} {{ currentPost.postTime }}</span>
						<span>评论数：{{ currentPost.commentCount }}</span>
						<span>状态：
							<el-tag :type="getStatusType(currentPost.status)" size="mini">
								{{ getStatusText(currentPost.status) }}
							</el-tag>
						</span>
					</div>
				</div>
				<div class="post-cover" v-if="currentPost.picUrl">
					<el-image :src="currentPost.picUrl" :fit="fit"></el-image>
				</div>
				<div class="post-content">{{ currentPost.content }}</div>

				<!-- 评论列表 -->
				<div class="comment-section" v-if="currentPost.comments && currentPost.comments.length">
					<h3>评论列表</h3>
					<div class="comment-list">
						<div v-for="comment in currentPost.comments" :key="comment._id" class="comment-item">
							<div class="comment-header">
								<span class="comment-author">{{ comment.isAnonymous ? '匿名用户' : comment.author }}</span>
								<span class="comment-time">{{ comment.createTime }}</span>
							</div>
							<div class="comment-content">{{ comment.content }}</div>
						</div>
					</div>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		name: 'ForumManage',
		data() {
			return {
        comment1:[],
        comment2:[],
				total: 0,
				// 搜索表单
				searchForm: {
					title: '',
					category: '',
					author: '',
					status: '',
					postDate: '',
					postTime: '',
					pageNo: 1
				},
				// 表格数据
				tableData: [],
				// 对话框
				dialogVisible: false,
				viewDialogVisible: false,
				dialogTitle: '',
				// 表单
				postForm: {
					category: '',
					title: '',
					content: '',
					pic: '',
					picUrl: '',
					postDate: '',
					postTime: '',
					status: '0',
					author: 'admin',
          remark:""
				},
				// 当前查看的帖子
				currentPost: {},
				// 表单验证规则
				rules: {
					category: [{
						required: true,
						message: '请选择帖子类型',
						trigger: 'change'
					}],
					title: [{
							required: true,
							message: '请输入帖子标题',
							trigger: 'blur'
						},
						{
							min: 2,
							max: 100,
							message: '长度在 2 到 100 个字符',
							trigger: 'blur'
						}
					],
					content: [{
							required: true,
							message: '请输入帖子内容',
							trigger: 'blur'
						},
						{
							min: 10,
							message: '内容不能少于10个字符',
							trigger: 'blur'
						}
					]
				}
			}
		},
		mounted() {
			this.fetchData(1)
		},
		methods: {
			// 获取帖子列表
			async fetchData(pageNo) {
				this.searchForm.pageNo = pageNo;
				this.tableData = [];
				const res = await this.$axios({
					url: '/api/queryalltopic',
					method: 'POST',
					data: this.searchForm
				})
				if (res && res.status === 200) {
					this.total = res.data.pager.Total;
					for (let i = 0; i < res.data.data.length; i++) {
						const temp = JSON.parse(res.data.data[i]);
						this.tableData.push(temp);
					}
				}
				if (this.tableData.length > 0) {
					let fileid_list = [];
					for (let i = 0; i < this.tableData.length; i++) {
						fileid_list.push(this.tableData[i].pic);
					}
					const picliist = await this.getFileTempUrl(fileid_list);
					for (let i = 0; i < picliist.length; i++) {
						if (this.tableData[i].pic === picliist[i].fileid) {
							this.tableData[i].picUrl = picliist[i].download_url;
						}
					}
				}
			},
			//加载图片
			async getFileTempUrl(fileid_list) {
				const res = await this.$axios({
					url: '/api/getfiletempurl',
					method: 'POST',
					data: fileid_list
				})
				if (res && res.status === 200) {
					return res.data.data;
				}
			},
			// 重置搜索
			resetSearch() {
				this.searchForm = {
					category: '',
					title: '',
					author: '',
					status: '',
					postDate: ''
				}
			},
			// 新增帖子
			handleAdd() {
				this.dialogTitle = '发布新帖'
				this.postForm = {
					category: '',
					title: '',
					content: '',
					pic: '',
					picUrl: '',
					postDate: '',
					postTime: '',
					status: '0',
					author: 'admin',
          remark: ''
				}
				this.dialogVisible = true
			},
			// 编辑帖子
			handleEdit(row) {
				this.dialogTitle = '编辑帖子'
				this.postForm = {
					...row
				}
				this.dialogVisible = true
			},
			// 查看帖子
			async handleView(row) {
				this.currentPost = row;
				this.viewDialogVisible = true;
				// 查询所有评论
				// await this.QueryAllComment(row._id);
				// 查询二级评论
			},
			// 查询所有评论
			// async QueryAllComment(_id){
			// 	const res = await this.$axios({
			// 		url:'/api/queryallcomment',
			// 		method:'POST',
			// 		data:{'comment_pr_id':_id}
			// 	})
      //   console.log('查询结果',res)
      //   for (let i=0;i<res.data.length;i++){
      //     let temp = JSON.parse(res.data[i]);
      //     temp.publisherinfo = await this.QueryUser(temp.publisherid);
      //     if(temp.parent_id===null){
      //       this.comment1.push(temp);
      //     }else{
      //       temp.
      //     }
      //   }
			// },
      // 查询用户信息
      // async QueryUser(_id){
      //   const res = await this.$axios({
      //     url:'/api/queryuser',
      //     method:'POST',
      //     data:{_id}
      //   })
      //   // console.log('查询结果',res);
      //   if(res.data.status===1){
      //     return res.data.data;
      //   }
      // },
			// 删除帖子
			handleDelete(row) {
				this.$confirm('确认删除该帖子吗？删除后将无法恢复', '提示', {
					type: 'warning'
				}).then(async () => {
					try {
						const res = await this.$axios({
							url: '/api/deletetopic',
							method: 'POST',
							data: {
								...row
							}
						})
						if (res.data.status === 1) {
							this.$message.success('删除成功')
							this.fetchData(1)
						} else {
							this.$message.error(res.msg || '删除失败')
						}
					} catch (error) {
						console.error('删除帖子失败:', error)
						this.$message.error('删除失败')
					}
				}).catch(() => {})
			},
			// 提交表单
			submitForm() {
				this.postForm.postDate = this.transformDate();
				this.postForm.postTime = this.transformTime();
				this.$refs.postForm.validate(async (valid) => {
					if (valid) {
						try {
							const url = this.postForm._id ? '/api/updatetopic' : '/api/addtopic'
							const res = await this.$axios({
								url,
								method: 'POST',
								data: this.postForm
							})
							if (res.data.status === 1) {
								this.$message.success(this.postForm._id ? '更新成功' : '发布成功')
								this.dialogVisible = false
								this.fetchData(1);
							} else {
								this.$message.error(res.msg || '操作失败')
							}
						} catch (error) {
							console.error('提交帖子失败:', error)
							this.$message.error('操作失败')
						}
					}
				})
			},
			// 处理当前日期
			transformDate() {
				const date = new Date();
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, "0");
				const day = String(date.getDate()).padStart(2, "0");
				return `${year}-${month}-${day}`;
			},
			// 处理当前时间
			transformTime() {
				const date = new Date();
				const hours = String(date.getHours()).padStart(2, "0");
				const minutes = String(date.getMinutes()).padStart(2, "0");
				return `${hours}:${minutes}`;
			},
			// 页码改变
			handleCurrentChange(val) {
				this.fetchData(val)
			},
			// 获取状态类型
			getStatusType(status) {
				const statusMap = {
					'0': 'info',
					'1': 'success',
					'2': 'danger'
				}
				return statusMap[status] || 'info'
			},
			// 获取状态文本
			getStatusText(status) {
				const statusMap = {
					'0': '待审核',
					'1': '已通过',
					'2': '已拒绝'
				}
				return statusMap[status] || '未知'
			},
			// 处理封面图片上传成功
			async handleCoverSuccess(res) {
				console.log("上传结果", res);
				if (res.status === 1) {
					this.postForm.pic = res.data.pic;
					const fileid_list = [this.postForm.pic];
					const piclist = await this.getFileTempUrl(fileid_list);
					this.postForm.picUrl = piclist[0].download_url;
				} else {
					this.$message.error('上传失败')
				}
			},
			// 上传前校验
			beforeCoverUpload(file) {
				const isImage = file.type.startsWith('image/')
				const isLt2M = file.size / 1024 / 1024 < 2

				if (!isImage) {
					this.$message.error('只能上传图片文件!')
					return false
				}
				if (!isLt2M) {
					this.$message.error('图片大小不能超过 2MB!')
					return false
				}
				return true
			},
			// 审核帖子
			handleAudit(row) {
				this.auditDialogTitle = '审核帖子'
				this.auditForm = {
					status: '1',
					auditRemark: '',
					topicIds: [row._id]
				}
				this.auditDialogVisible = true
			},
			// 批量审核
			handleBatchAudit() {
				if (this.selectedTopics.length === 0) {
					this.$message.warning('请选择要审核的帖子')
					return
				}
				this.auditDialogTitle = '批量审核'
				this.auditForm = {
					status: '1',
					auditRemark: '',
					topicIds: this.selectedTopics.map(item => item._id)
				}
				this.auditDialogVisible = true
			},
			// 提交审核
			submitAudit() {
				this.$refs.auditForm.validate(async (valid) => {
					if (valid) {
						try {
							const res = await this.$axios({
								url: '/api/audittopic',
								method: 'POST',
								data: this.auditForm
							})
							if (res.status === 1) {
								this.$message.success('审核成功')
								this.auditDialogVisible = false
								this.fetchData()
							} else {
								this.$message.error(res.msg || '审核失败')
							}
						} catch (error) {
							console.error('审核失败:', error)
							this.$message.error('审核失败')
						}
					}
				})
			}
		}
	}
</script>

<style scoped>
	.pagination-container {
		margin-top: 20px;
		text-align: right;
	}

	.post-detail {
		padding: 20px;
	}

	.post-header {
		margin-bottom: 20px;
	}

	.post-title {
		margin: 0 0 20px;
		font-size: 24px;
		color: #303133;
		text-align: center;
	}

	.post-meta {
		margin-bottom: 20px;
		color: #909399;
		font-size: 14px;
		text-align: center;
	}

	.post-meta span {
		margin: 0 10px;
	}

	.post-cover {
		margin-bottom: 20px;
		text-align: center;
	}

	.post-cover .el-image {
		max-width: 100%;
		max-height: 400px;
	}

	.post-content {
		line-height: 1.8;
		color: #606266;
		white-space: pre-wrap;
		margin-bottom: 30px;
	}

	.comment-section {
		margin-top: 30px;
		border-top: 1px solid #EBEEF5;
		padding-top: 20px;
	}

	.comment-section h3 {
		margin-bottom: 20px;
		font-size: 18px;
		color: #303133;
	}

	.comment-item {
		padding: 15px;
		border-bottom: 1px solid #EBEEF5;
	}

	.comment-header {
		margin-bottom: 10px;
	}

	.comment-author {
		font-weight: bold;
		color: #303133;
		margin-right: 10px;
	}

	.comment-time {
		color: #909399;
		font-size: 12px;
	}

	.comment-content {
		color: #606266;
		line-height: 1.6;
	}

	.avatar-uploader {
		text-align: center;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 200px;
		height: 100px;
		line-height: 100px;
		text-align: center;
	}

	.avatar {
		width: 200px;
		height: 100px;
		display: block;
		object-fit: cover;
	}

	.upload-tip {
		font-size: 12px;
		color: #909399;
		margin-top: 5px;
	}

	.el-input {
		width: 400px;
	}

	.el-select {
		width: 400px;
	}

	.el-date-editor.el-input {
		width: 360px;
	}
</style>